/**
 * 游戏主体
 */
class Game extends egret.DisplayObjectContainer {
    private mapItem: MapItem = new MapItem();
    private roleItem: RoleItem = new RoleItem();

    constructor() {
        super();
        this.once(egret.Event.ADDED_TO_STAGE, this.init, this);
    }
    private init() {
        const miva = this;
        // 初始化游戏
        ParamPool.QUESTION_BOX = RES.getRes("question_json");
        ParamPool.GAME_PAUSE = false;
        // 生成道具
        miva.createMapItem();
        miva.createRole();
        miva.controleRole();
        miva.questionCreate();
        miva.createBestScorePanel();
        // miva.createScorePanel();
        miva.createBgmControle();
        miva.createGameRule();

        for (let i = 1; i <= 5; i++) miva.createGoal(i);

        // 监听帧事件
        miva.addEventListener(egret.Event.ENTER_FRAME, miva.update, miva);
    }
    // 帧事件钩子
    private update() {
        if (!ParamPool.GAME_PAUSE) return;
        const miva = this;

        miva.mapItem.x -= ParamPool.GAME_SPEED;
        miva.scorePanelNow.text = `${ParamPool.TOTAL_SCORE}`;
        // 收集移动距离
        const moveDistance = Math.abs(miva.mapItem.x);
        if (moveDistance % 500 == 0) {
            console.log("刷出一个敌人");
            miva.createRival();
        }

        miva.goalHit();
        miva.rivalHit();
    }
    // 背景音乐控制器
    private createBgmControle() {
        const miva = this;
        const musicItem = new MusicItem();
        miva.addChild(musicItem);
        musicItem.x = miva.stage.stageWidth - musicItem.width - 80;
        musicItem.y = 30;
    }
    // 创建地图
    private createMapItem() {
        const miva = this;
        miva.addChild(miva.mapItem);
    }
    // 创建游戏规则提示
    private createGameRule() {
        const miva = this;
        const container = new egret.Sprite();
        const rule_png = Main.createBitmapByName("rule_png");
        const close_btn = Main.createBitmapByName("ok_btn_png");

        Main.anchorCenter(rule_png);
        rule_png.x = miva.stage.stageWidth / 2;
        rule_png.y = miva.stage.stageHeight / 2;
        close_btn.x = 450;
        close_btn.y = 520;
        close_btn.touchEnabled = true;
        close_btn.addEventListener(egret.TouchEvent.TOUCH_TAP, () => {
            miva.removeChild(container);
            miva.createCountDown();
        }, miva);

        miva.addChild(container);
        container.addChild(rule_png);
        container.addChild(close_btn);

        container.touchEnabled = true;
        container.addEventListener(egret.TouchEvent.TOUCH_BEGIN, Main.superStopPropagation, miva);
        container.addEventListener(egret.TouchEvent.TOUCH_MOVE, Main.superStopPropagation, miva);
        container.addEventListener(egret.TouchEvent.TOUCH_END, Main.superStopPropagation, miva);
    }
    // 创建游戏开始倒计时与提示
    private createCountDown() {
        const miva = this;
        const countDownTimer = new egret.Timer(1000, 3);
        const num_png = Main.createBitmapByName("num_3_png");
        const controleTip = Main.createBitmapByName("tip_png");
        let timer_num = 3;

        Main.anchorCenter(num_png);
        num_png.x = miva.stage.stageWidth / 2;
        num_png.y = miva.stage.stageHeight / 2 - 100;

        Main.anchorCenter(controleTip);
        controleTip.x = this.stage.stageWidth / 2;
        controleTip.y = this.stage.stageHeight / 2 + 100;

        miva.addChild(controleTip);
        miva.addChild(num_png);

        countDownTimer.addEventListener(egret.TimerEvent.TIMER, () => {
            timer_num--;
            num_png.texture = RES.getRes(`num_${timer_num}_png`);
        }, miva);
        countDownTimer.addEventListener(egret.TimerEvent.TIMER_COMPLETE, () => {
            miva.removeChild(num_png);
            miva.removeChild(controleTip);
            ParamPool.GAME_PAUSE = true;
        }, this);

        countDownTimer.start();
    }
    // 添加成绩板
    private scorePanelNow = new eui.Label();
    private createScorePanel() {
        const miva = this;
        const container = new egret.Sprite();
        const scorePanel_png = Main.createBitmapByName("timer_item_png");

        container.addChild(scorePanel_png);
        container.addChild(miva.scorePanelNow);
        miva.addChild(container);

        container.x = 80;
        container.y = 30;
        miva.scorePanelNow.x = 85;
        miva.scorePanelNow.y = 15;
        miva.scorePanelNow.text = `${ParamPool.TOTAL_SCORE}`;
    }
    // 添加历史成绩面板
    private scorePanelBest = new eui.Label();
    private createBestScorePanel() {
        const miva = this;
        const container = new egret.Sprite();
        const scorePanel_png = Main.createBitmapByName("histroy_png");

        container.addChild(scorePanel_png);
        container.addChild(miva.scorePanelBest);
        container.addChild(miva.scorePanelNow);
        miva.addChild(container);

        container.x = 80;
        container.y = 30;
        miva.scorePanelBest.x = 130;
        miva.scorePanelBest.y = 5;
        miva.scorePanelBest.text = `${ParamPool.BEST_SCORE}`;

        miva.scorePanelNow.x = 330;
        miva.scorePanelNow.y = 5;
        miva.scorePanelNow.text = `${ParamPool.TOTAL_SCORE}`;

    }
    // 添加主角到舞台中
    private createRole() {
        const miva = this;
        miva.addChild(miva.roleItem);
        miva.roleItem.x = 300;
        miva.roleItem.y = miva.mapItem.mid;
    }
    // 操作角色
    private controleRole() {
        const miva = this;
        // 初始触摸点
        const startPoint = new egret.Point();
        const comput = new egret.Point();

        miva.touchEnabled = true;
        miva.addEventListener(egret.TouchEvent.TOUCH_BEGIN, (evt: egret.TouchEvent) => {
            startPoint.x = evt.stageX;
            startPoint.y = evt.stageY;
            miva.stage.addEventListener(egret.TouchEvent.TOUCH_MOVE, touchMoveHandler, miva);
            miva.stage.once(egret.TouchEvent.TOUCH_END, touchEndHandler, miva);
        }, miva);

        function touchMoveHandler(evt: egret.TouchEvent) {
            comput.y = evt.stageY - startPoint.y;
        }
        function touchEndHandler(evt: egret.TouchEvent) {
            miva.stage.removeEventListener(egret.TouchEvent.TOUCH_MOVE, touchMoveHandler, miva);
            comput.y < 0 ? miva.roleTT() : miva.roleDD();
        }
    }
    // 角色上移操作
    private roleTT() {
        const miva = this;
        let move = null;
        if (miva.roleItem.y == miva.mapItem.mid) move = miva.mapItem.top;
        if (miva.roleItem.y == miva.mapItem.btm) move = miva.mapItem.mid;
        if (move) egret.Tween.get(miva.roleItem).to({ y: move }, 200);
        console.log("角色上移");
    }
    // 角色下移操作
    private roleDD() {
        const miva = this;
        let move = null;
        if (miva.roleItem.y == miva.mapItem.mid) move = miva.mapItem.btm;
        if (miva.roleItem.y == miva.mapItem.top) move = miva.mapItem.mid;
        if (move) egret.Tween.get(miva.roleItem).to({ y: move }, 200);
        console.log("角色下移");
    }
    // 添加对手到舞台中
    private createRival() {
        const miva = this;
        const rivalItem = new RivalItem();
        const random = Math.random() * 90;

        miva.addChild(rivalItem);

        rivalItem.x = miva.stage.stageWidth;
        if (random < 30) {
            rivalItem.y = miva.mapItem.top;
            miva.swapChildren(miva.roleItem, rivalItem);
        } else if (random > 60) {
            rivalItem.y = miva.mapItem.mid;
            miva.swapChildren(miva.roleItem, rivalItem);
        } else {
            rivalItem.y = miva.mapItem.btm;
        }

        ParamPool.RIVAL_POOL.push({ item: rivalItem, isLive: true });

        egret.Tween.get(rivalItem).to({ x: -100 }, 1000).call(() => {
            miva.removeChild(rivalItem);
            ParamPool.RIVAL_POOL.shift();
        });

    }
    // 题目初始化
    private questionCreate() {
        ParamPool.QUESTION_A = ParamPool.QUESTION_BOX["高新地产问题："];
        ParamPool.QUESTION_B = ParamPool.QUESTION_BOX["足球类问题："];
    }
    // 抽取题目方法
    private getQuestion() {
        let num = 0;
        let res = null;

        ParamPool.QUESTION_NUM <= 4 ? handler(ParamPool.QUESTION_A) : handler(ParamPool.QUESTION_B);

        function handler(item: Array<any>) {
            num = Math.floor(Math.random() * (item.length - 1));
            res = item[num];
            item.splice(num, 1);
            console.log(res, num, item)
        }

        return res;
    }
    // 把球门添加到舞台中
    createGoal(num = 1) {
        const miva = this;
        const goal = new Goal();
        miva.mapItem.addChild(goal);
        ParamPool.GOAL_POOL.push({ item: goal, isLive: true });

        goal.x = num * 2600;
        goal.y = this.stage.stageHeight / 2;
    }
    // 球门碰撞检测
    goalHit() {
        const miva = this;
        for (let i = 0; i < ParamPool.GOAL_POOL.length; i++) {
            const isGoalHit = ParamPool.GOAL_POOL[i].item.hitTestPoint(miva.roleItem.trueItem.x + 300, miva.roleItem.trueItem.y);
            if (isGoalHit && ParamPool.GOAL_POOL[i].isLive) {
                // 暂停跑动
                ParamPool.GAME_PAUSE = false;
                // 杀死这个球门
                ParamPool.GOAL_POOL[i].isLive = false;
                // 题号+1
                ParamPool.QUESTION_NUM++;
                // 弹出题目
                const shoot = new Shoot(miva.getQuestion());
                miva.addChild(shoot);
                console.log("开始答题");
            }
        }
    }
    // 对手碰撞检测
    rivalHit() {
        const miva = this;

        for (let i = 0; i < ParamPool.RIVAL_POOL.length; i++) {
            const isHit = miva.roleItem.trueItem.hitTestPoint(ParamPool.RIVAL_POOL[i].item.x, ParamPool.RIVAL_POOL[i].item.y + 20);
            if (isHit && ParamPool.RIVAL_POOL[i].isLive) {
                // 杀死这个对手
                ParamPool.RIVAL_POOL[i].isLive = false;
                ParamPool.TOTAL_SCORE -= ParamPool.DEDUCTION;
                // 主角闪烁
                egret.Tween.get(miva.roleItem)
                    .to({ alpha: 0 })
                    .wait(100)
                    .to({ alpha: 1 })
                    .wait(100)
                    .to({ alpha: 0 })
                    .wait(100)
                    .to({ alpha: 1 })
                    .wait(100)
                    .to({ alpha: 0 })
                    .wait(100)
                    .to({ alpha: 1 });
                console.log("扣分");
            }
        }
    }
}